package com.douding.server.service;

import com.douding.server.domain.Chapter;
import com.douding.server.domain.ChapterExample;
import com.douding.server.dto.ChapterDto;
import com.douding.server.dto.ChapterPageDto;
import com.douding.server.mapper.ChapterMapper;
import com.douding.server.mapper.SectionMapper;
import com.douding.server.util.CopyUtil;
import com.douding.server.util.UuidUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.List;

@Service
public class ChapterService {

    @Resource
    private ChapterMapper chapterMapper;

    @Resource
    private SectionMapper sectionMapper;


    public void list(ChapterPageDto chapterPageDto) {
        PageHelper.startPage(chapterPageDto.getPage(), chapterPageDto.getSize());
        ChapterExample example = new ChapterExample();
        example.createCriteria().andCourseIdEqualTo(chapterPageDto.getCourseId());
        List<Chapter> chapters = chapterMapper.selectByExample(example);
        PageInfo<Chapter> pageInfo = new PageInfo<>(chapters);
        chapterPageDto.setTotal(pageInfo.getTotal());
        List<ChapterDto> chapterDtos = CopyUtil.copyList(chapters, ChapterDto.class);
        chapterPageDto.setList(chapterDtos);
    }// method


    public void save(ChapterDto chapterDto) {
        String id = chapterDto.getId();
        Chapter chapter = CopyUtil.copy(chapterDto, Chapter.class);
        if (!StringUtils.isEmpty(id)) {
            update(chapter);
            return;
        }
        insert(chapter);
    }
    //新增数据
    private void insert(Chapter chapter) {
        chapter.setId(UuidUtil.getShortUuid());
        chapterMapper.insert(chapter);
    }
    //更新数据
    private void update(Chapter chapter) {
        ChapterExample chapterExample = new ChapterExample();
        chapterExample.createCriteria().andIdEqualTo(chapter.getId());
        chapterMapper.updateByExample(chapter, chapterExample);
    }

    public void delete(String id) {
        // 删除chapter表数据
        chapterMapper.deleteByPrimaryKey(id);
        // 删除section表中包含id的数据
        sectionMapper.deleteByPrimaryKey(id);
    }


    /**
     * 查询某一课程下的所有章
     */
    public List<ChapterDto> listByCourse(String courseId) {
        ChapterExample example = new ChapterExample();
        example.createCriteria().andCourseIdEqualTo(courseId);
        List<Chapter> chapters = chapterMapper.selectByExample(example);
        return CopyUtil.copyList(chapters, ChapterDto.class);
    }
}//end class
